package ch.uzh.ifi.seal.ssqa.metrics.commands;

import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.eclipse.draw2d.IFigure;
import org.eclipse.draw2d.Label;
import org.eclipse.gmf.runtime.diagram.ui.editparts.GraphicalEditPart;
import org.eclipse.gmf.runtime.diagram.ui.parts.DiagramGraphicalViewer;
import org.eclipse.gmf.runtime.notation.Shape;
import org.eclipse.gmf.runtime.notation.View;
import org.eclipse.swt.graphics.Color;

import ch.uzh.ifi.seal.ssqa.metrics.heatmap.IHeatMap;
import ch.uzh.ifi.seal.ssqa.model.DiagramComponent;
import ch.uzh.ifi.seal.ssqa.util.ColorHelper;
import ch.uzh.ifi.seal.ssqa.util.ValueNormalizer;

public class ApplyHeatMapCommand implements IApplyMetricCommand {

	DiagramGraphicalViewer viewer;
	IHeatMap metric;
	
	public ApplyHeatMapCommand(DiagramGraphicalViewer viewer, IHeatMap metric){
		this.viewer = viewer; 
		this.metric = metric;
	}
	
	@Override
	public void execute(){
		Map<String, Double> heatMapping = this.metric.getHeatMapping();
		
		Map registry = this.viewer.getEditPartRegistry();
		Set set = registry.keySet();
		Iterator iterator = set.iterator();
		
		while(iterator.hasNext()){
			Object key  = iterator.next();
			if(key instanceof Shape){
				GraphicalEditPart editpart = (GraphicalEditPart) this.viewer.getEditPartRegistry().get(key);
				Label toolTip = new Label(metric.getName()+": "+heatMapping.get((DiagramComponent)((View)key).getElement()));
				editpart.getFigure().setToolTip(toolTip);
				List<IFigure> list = editpart.getFigure().getChildren();
				for(IFigure figure : list){
					Color color = ColorHelper.getNormalizedColor(ValueNormalizer.normalizeValue(heatMapping.get(((DiagramComponent)((View)key).getElement()).getIdentifier()), this.metric.getMaxValue(), this.metric.getMinValue()));
					figure.setBackgroundColor(color);
					figure.setToolTip(toolTip);
				}
			}
		}
	}
}
